package yyds.sniarbtej;

import org.apache.commons.codec.binary.Base64;

import java.io.File;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;

public class LicenseManager {

    private static boolean checkKey(File license) {
        if (!license.exists()) {
            return false;
        } else {
            try {
                byte[] var3 = Files.readAllBytes(Paths.get(license.getAbsolutePath()));
                if (var3[0] != -1 || var3[1] != -1) {
                    return false;
                }

                String[] keyParts = (new String(var3, 2, var3.length - 2, StandardCharsets.UTF_16LE)).split("\n")[1].split("-");
                if (keyParts.length != 4) {
                    return false;
                }

                String json = new String(Base64.decodeBase64(keyParts[1]));
                String signature = keyParts[2];
                if (LicenseGenerator.getSignature(json).equals(signature)) {
                    return true;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            return false;
        }
    }

    private static void writeDefaultKey(File licenseFile, String license) {
        try {
            byte[] key = ("<certificate-key>\n" + license).getBytes(StandardCharsets.UTF_16LE);
            byte[] certificate = new byte[key.length + 2];
            certificate[0] = -1;
            certificate[1] = -1;
            System.arraycopy(key, 0, certificate, 2, key.length);
            Files.write(Paths.get(licenseFile.getAbsolutePath()), certificate);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void checkLicenseFile(File license) {
        try {
            if (!checkKey(license)) {
                System.out.println("checkKey failed, generating default key...   : " + license.getName());
                writeDefaultKey(license, LicenseGenerator.getDefaultKey());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
